/*
package com.mingchuang.administrator.mingchuang.wifi;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.List;


public class WifiReceive extends Activity {

	private TextView ReceiveRemind = null;// 提醒客户用的text
	private RelativeLayout progresscontainer = null;// 包含进度条的layout
	private ProgressBar Cyclepb = null;// 等待对方连接圆形进度
	private ProgressBar Horipb = null;// 接受信息进度
	private CheckTimeoutThread m_CheckTimeoutThread = null;// 用于检测服务端等待超时的线程

	static List<Byte> Bl = new LinkedList<Byte>();
	static FileOutputStream Rev_Fs;

	private boadIpThread boadIP = null;
	private String username = null;
	private String MobileName = null;
	private String OpponentIP = null;

	private static final int CONFIRM = 11;
	public static final byte CONFIRM_FLAG = 0;
	public static final byte CANCEL_FLAG = 1;

	private DatagramSocket datasocket = null;
	private ServerSocket connectss = null;
	private Socket connectsocket = null;
	private ServerSocket getVcardss = null;
	private Socket getVcardsocket = null;

	private final Handler mHandler = new Handler() {
		Bundle b = null;

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case WifiHelper.WIFICONNECT:
					showDialog(CONFIRM);// 调用onCreateDialog
					break;
				case WifiHelper.UDP_SEND:
					ReceiveRemind.setGravity(Gravity.CENTER);
					ReceiveRemind.setText(getString(R.string.udp_send));
					break;
				case Constant.SERVICE_ON:
					ReceiveRemind.setGravity(Gravity.CENTER);
					ReceiveRemind.setText(getString(R.string.server_start));
					break;
				case Constant.MESSAGE_CONNECTED:
					// 使用interrupt停止检测超时线程的运行
					m_CheckTimeoutThread.interrupt();
					m_CheckTimeoutThread = null;
					ReceiveRemind.setGravity(Gravity.CENTER);
					ReceiveRemind.setText(getString(R.string.receiving));
					progresscontainer.removeView(Cyclepb);
					break;
				case Constant.INIT_PROG:
					b = msg.getData();
					int max = b.getInt("Total");
					Horipb.setMax(max);
					RelativeLayout.LayoutParams barlp = new RelativeLayout.LayoutParams(
							ViewGroup.LayoutParams.FILL_PARENT, // width
							ViewGroup.LayoutParams.WRAP_CONTENT // height

					);
					UnitSize.mysetMargins(WifiReceive.this, barlp, 0, 100, 0, 0);
					progresscontainer.addView(Horipb, barlp);

					Horipb.setVisibility(View.VISIBLE);
					break;
				case Constant.UPDATE_PROG:
					b = msg.getData();
					int progress = b.getInt("Progress");
					Horipb.setProgress(progress);
					break;
				case Constant.CONNECT_TIMEOUT:
					AlertDialog dlg4 = new AlertDialog.Builder(WifiReceive.this)
							.setTitle("超时操作").setMessage(
									"您已等待较长时间，是否返回重新操作？选择“是”返回，选择“否”继续等待。")
							.setPositiveButton("是",
									new DialogInterface.OnClickListener() {

										public void onClick(DialogInterface dialog,
															int which) {
											onBackPressed();
										}
									}).setNeutralButton("否",
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,
															int witch) {
											dialog.dismiss();
											// 监听后运行超时检测线程
											m_CheckTimeoutThread = new CheckTimeoutThread(
													mHandler);
											m_CheckTimeoutThread.start();
										}
									}).create();
					dlg4.show();
					break;
				case Constant.MESSAGE_RECEIVED:
					Horipb.setVisibility(View.INVISIBLE);
					Intent i = new Intent(WifiReceive.this, importing.class);
					i.putExtra("filepath", WifiHelper.WIFIRECEIVEPATH);
					startActivity(i);
					break;
			}
		}
	};

	*/
/************** 提示对话框 ***************//*

	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case CONFIRM:
				String tempstring = "您是否确认接受对方用户的链接请求：" + MobileName;
				return new AlertDialog.Builder(WifiReceive.this).setTitle("温馨提示")
						.setMessage(tempstring).setIcon(
								android.R.drawable.ic_dialog_info)
						.setPositiveButton("确认", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {

								SendResponseThread sp = new SendResponseThread(
										CONFIRM_FLAG);
								sp.start();
								// 启动接收线程
								ServerThread server = new ServerThread(mHandler);
								server.start();
							}
						}).setNegativeButton("取消", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								SendResponseThread sp = new SendResponseThread(
										CANCEL_FLAG);
								sp.start();
							}
						}).create();
			default:
				return null;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.btserverfetch);
		setContentView(R.layout.wifireceive);
		progresscontainer = (RelativeLayout) findViewById(R.id.progresscontainer);
		Horipb = (ProgressBar) findViewById(R.id.importbar);
		Cyclepb = (ProgressBar) findViewById(R.id.cyclebar);
		ReceiveRemind = (TextView) findViewById(R.id.btservertext);
		String ss = getString(R.string.building_server);

		progresscontainer.removeView(Horipb);
		ReceiveRemind.setText(ss);
		RelativeLayout.LayoutParams barlp = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT, // width
				ViewGroup.LayoutParams.WRAP_CONTENT // height

		);
		UnitSize.mysetMargins(WifiReceive.this, barlp, 135, 100, 0, 0);
		progresscontainer.removeView(Cyclepb);
		progresscontainer.addView(Cyclepb, barlp);

		Cyclepb.setVisibility(View.VISIBLE);

		Intent intent = getIntent();
		username = intent.getStringExtra("username");

		DatagramSocket ds;
		try {
			ds = new DatagramSocket(WifiHelper.UDP_BOADCASTPORT);
			ds.setBroadcast(true);

			// 创建并启动发送线程
			boadIP = new boadIpThread(username, ds);
			boadIP.start();
			mHandler.obtainMessage(WifiHelper.UDP_SEND).sendToTarget();
		} catch (SocketException e1) {
			System.out.println("广播IP的Socket错了");
			e1.printStackTrace();
		} catch (Exception e) {
			System.out.println("广播IP的Socket错了");
			e.printStackTrace();
		}
		// 启动connect请求监听线程
		GetConnectThread connect = new GetConnectThread(mHandler);
		connect.start();

	}

	*/
/**
	 * 广播自己用户名的线程
	 *
	 * @author XijieChen
	 *
	 *//*

	class boadIpThread extends Thread {

		private String username;

		public boadIpThread(String name, DatagramSocket dsocket)
				throws Exception {
			username = name;
			datasocket = dsocket;
		}

		public void run() {
			try {
				while (true) {
					// 构造发送数据报 把自己的名字发送出去
					byte[] data = username.getBytes();
					DatagramPacket outgoing = new DatagramPacket(data,
							data.length, InetAddress
							.getByName("255.255.255.255"),
							WifiHelper.UDP_BOADCASTPORT);
					// 发送数据报
					datasocket.send(outgoing);

					System.out.println("广播IP地址");
					Thread.sleep(1000);// 每秒广播一次
				}
			} catch (Exception ee) {
				System.out.println("广播IP地址的socket出错");
			} finally {
				// 关闭dsocket
				System.out.println("关闭广播IP地址的socket");

				if (datasocket != null)
					datasocket.close();
			}
		}
	}

	*/
/***
	 * 监听发送方connect请求的线程
	 *
	 * @author XijieChen
	 *
	 *//*

	class GetConnectThread extends Thread {
		private InputStream instrm = null;
		private final Handler tHandler;

		GetConnectThread(Handler handler) {
			tHandler = handler;
		}

		public void run() {

			try {
				connectss = new ServerSocket(WifiHelper.TCP_CONNECTPORT);
				System.out.println("ConnectListening...");

				// accept阻塞直到被连接
				connectsocket = connectss.accept();
				System.out.println("ConnectThread Connected...");

				// 阻塞运行
				instrm = connectsocket.getInputStream();
				MobileName = getMobilename(instrm);
				tHandler.obtainMessage(WifiHelper.WIFICONNECT).sendToTarget();

				OpponentIP = connectsocket.getInetAddress().toString();
				OpponentIP = OpponentIP.substring(1);
				System.out.println("发送方的IP地址==" + OpponentIP);
				boadIP = null;// 终止boadIP线程，即停止广播
				datasocket.close();

			} catch (Exception e) {

				System.out.println("Connect请求线程出错");
				e.printStackTrace();
			}
		}
	}

	private String getMobilename(InputStream instrm) {

		byte[] buffer = new byte[WifiHelper.NAME_BUFFER_LENGTH];
		try {
			instrm.read(buffer);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String newstr = new String(buffer);
		System.out.println("对方用户名==" + newstr);
		return newstr;
	}

	*/
/**
	 * 向发送方发送响应的线程
	 *
	 * @author XijieChen
	 *
	 *//*

	class SendResponseThread extends Thread {

		private OutputStream outStrm = null;
		byte flag = 0;

		public SendResponseThread(byte FLAG) {
			flag = FLAG;
		}

		public void run() {
			try {
				// 阻塞运行
				outStrm = connectsocket.getOutputStream();
				outStrm.write(flag & 0x000000ff);
				System.out.println("发送响应的flag==" + flag);

				if (flag == CANCEL_FLAG) {
					onBackPressed();
				}
				outStrm.close();
				connectsocket.close();
				connectss.close();
			} catch (IOException e) {

				try {
					if (connectss != null)
						connectss.close();
					if (connectsocket != null)
						connectsocket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				try {
					if (outStrm != null)
						outStrm.close();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	private class CheckTimeoutThread extends Thread {
		Handler mhandler = null;

		CheckTimeoutThread(Handler mhandler) {
			this.mhandler = mhandler;
		}

		public void run() {
			try {
				Thread.sleep(WifiHelper.timecheck);
				mhandler.obtainMessage(Constant.CONNECT_TIMEOUT).sendToTarget();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
			}
		}
	}

	*/
/**
	 * 按照协议接收文件的线程
	 *
	 * @author XijieChen
	 *//*

	class ServerThread extends Thread {

		private InputStream instrm = null;
		private OutputStream outstream = null;
		private final Handler tHandler;
		byte ack[] = new byte[3];// 这个ack数组是为了强制双方数据传递同步

		ServerThread(Handler handler) {
			tHandler = handler;
			ack[0] = 'a';
			ack[1] = 'c';
			ack[2] = 'k';
		}

		public void run() {
			byte headtype = 0;

			try {
				getVcardss = new ServerSocket(WifiHelper.TCP_TRANSMISSIONPORT);
				System.out.println("接收文件的Listening...");

				tHandler.obtainMessage(Constant.SERVICE_ON).sendToTarget();
				// 监听后运行超时检测线程
				m_CheckTimeoutThread = new CheckTimeoutThread(tHandler);
				m_CheckTimeoutThread.start();
				// accept阻塞直到被连接
				getVcardsocket = getVcardss.accept();
				System.out.println("接收Vcard的Client Connected...");

				tHandler.obtainMessage(Constant.MESSAGE_CONNECTED)
						.sendToTarget();
				// 阻塞运行
				instrm = getVcardsocket.getInputStream();
				headtype = (byte) instrm.read();

				outstream = getVcardsocket.getOutputStream();
				outstream.write(ack);

				Rev_Fs = new FileOutputStream(new File(
						WifiHelper.WIFIRECEIVEPATH));
				ReceiveContent(headtype, instrm, outstream, ack);

				tHandler.obtainMessage(Constant.MESSAGE_RECEIVED)
						.sendToTarget();
				getVcardsocket.close();
				getVcardss.close();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (getVcardsocket != null)
						getVcardsocket.close();
					if (getVcardss != null)
						getVcardss.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	*/
/************ 接收文件的内容 *************//*

	private static void ReceiveContent(byte headtype, InputStream instrm,
									   OutputStream outstream, byte ack[]) {

		if (headtype == BluetoothCS.END)
			return;
		byte lengthhighhigh, lengthhighlow, lengthlowhigh, lengthlowlow;
		try {
			System.out.println("从这里开始接收文件");
			// lengthhighhigh = (byte) instrm.read();
			// lengthhighlow = (byte) instrm.read();
			// lengthlowhigh = (byte) instrm.read();
			// lengthlowlow = (byte) instrm.read();
			byte[] lengthbyte = new byte[4];
			instrm.read(lengthbyte);
			lengthhighhigh = lengthbyte[3];
			lengthhighlow = lengthbyte[2];
			lengthlowhigh = lengthbyte[1];
			lengthlowlow = lengthbyte[0];

			int ContentLength = fourBytetoInt(lengthhighhigh, lengthhighlow,
					lengthlowhigh, lengthlowlow);

			System.out.println("length is " + ContentLength);

			outstream.write(ack);

			byte[] buffer = new byte[WifiHelper.WIFI_BUFFER_LENGTH];
			int left = ContentLength;
			int readonce = 0;
			while (left > 0) {
				readonce = instrm.read(buffer);
				outstream.write(ack);
				left = left - readonce;

				System.out.println("left1 length is " + left);
				Rev_Fs.write(buffer, 0, readonce);
				for (int i = 0; i < readonce; i++) {
					Bl.add(new Byte(buffer[i]));
				}
				System.out.println("left2 length is " + left);
			}
			instrm.close();
			outstream.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			try {
				instrm.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}

	}

	*/
/************* 合并文件的高低字节以得到文件的长度 **************//*

	public static int fourBytetoInt(byte Highhigh, byte Highlow, byte Lowhigh,
									byte Lowlow) {
		int Int = 0;
		Int = Highhigh;
		Int = (int) (Int << 24);
		Int = Int + (0x00FF0000 & ((int) Highlow << 16));
		Int = Int + (0x0000FF00 & ((int) Lowhigh << 8));
		Int = Int + (0x000000FF & ((int) Lowlow));
		return Int;
	}

	*/
/*************** 点击了“返回”按钮 *****************//*

	public void onmain(View view) {
		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// onBackPressed();
		Intent i = new Intent(WifiReceive.this, NewMain.class);
		i.setFlags(i.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
	}

	@Override
	protected void onStop() {
		boadIP = null;
		if (datasocket != null) {
			datasocket.close();
		}

		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (connectsocket != null)
				connectsocket.close();
			if (connectss != null)
				connectss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onStop();
	}

	@Override
	public void onBackPressed() {
		boadIP = null;
		if (datasocket != null) {
			datasocket.close();
		}

		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (connectsocket != null)
				connectsocket.close();
			if (connectss != null)
				connectss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onBackPressed();
	}

}
*/
